package com.tencent.wxcloudrun.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author yuyongkang
 * @Date 2025/9/18 14:27
 */
public class LoginInterceptor implements HandlerInterceptor {


    private String jwtSecret;

    public LoginInterceptor(String jwtSecret) {
        this.jwtSecret = jwtSecret;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 从请求头获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            response.setStatus(401); // 未登录
            return false;
        }

        // 2. 验证token合法性
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtSecret)
                    .parseClaimsJws(token)
                    .getBody();
            // 3. 将openid存入请求属性，供后续接口使用
            request.setAttribute("openid", claims.getSubject());
            return true;
        } catch (Exception e) {
            response.setStatus(401); // token无效或过期
            return false;
        }
    }

}
